#include <moose.h>

#include <dlfcn.h>

moose_dynamic_lib_s* moose_dynamic_lib_load(const char* file, int len)
{
    /* Malloc moose_dynamic_lib_s */
    assert((file != NULL) && (len > 0));
    moose_dynamic_lib_s* a_lib = (moose_dynamic_lib_s*)calloc(1, sizeof(moose_dynamic_lib_s));
    assert(a_lib);

    /* Malloc filename */
    a_lib->filename = (char*)calloc(1, len+1);
    assert(a_lib->filename);
    memcpy(a_lib->filename, file, len);

    /* Open dynamic library */
    printf("[moose_dynamic_lib_load] start dlopen: %s\n", a_lib->filename);
    a_lib->handle = dlopen(a_lib->filename, RTLD_LAZY);
    if (a_lib->handle == NULL) {
        printf("[moose_dynamic_lib_load] %s\n", dlerror());
        moose_dynamic_lib_unload(a_lib); 
        return NULL;
    }
    printf("[moose_dynamic_lib_load] dlopen success!\n");

    a_lib->fn_load = (fn_moose_dynamic_lib_load)dlsym(a_lib->handle, "load");
    a_lib->fn_start = (fn_moose_dynamic_lib_start)dlsym(a_lib->handle, "start");
    a_lib->fn_unload = (fn_moose_dynamic_lib_start)dlsym(a_lib->handle, "unload");

    return a_lib;
}
void moose_dynamic_lib_unload(moose_dynamic_lib_s* lib)
{
    if (lib == NULL) {
        return ;
    }

    if (lib->handle != NULL) {
        dlclose(lib->handle);
        lib->handle = NULL;
    }

    if (lib->filename != NULL) {
        free(lib->filename);
        lib->filename = NULL;
    }

    free(lib);
}
